<template>
    <div class="anime-character-wrapper">
        <!-- Three.js容器 -->
        <div ref="container" class="character-container"></div>
    </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue';
import * as THREE from 'three';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';

// 容器引用
const container = ref(null);

// Three.js 变量
let scene, camera, renderer, character, controls, animationId;
let clock = new THREE.Clock();

// 颜色配置
const colors = {
    skin: 0xffe0bd,          // 皮肤
    hair: 0x9b59b6,          // 紫色头发
    eyes: 0x4d4dff,          // 蓝色眼睛
    dress: 0xff80ab,         // 粉色连衣裙
    shoes: 0x333333,         // 黑色鞋子
    blush: 0xff9999,         // 腮红
    mouth: 0xff6b6b,         // 嘴巴
    hairAccessory: 0xffffff  // 白色发饰
};

// 初始化Three.js
const initThree = () => {
    // 创建场景
    scene = new THREE.Scene();
    scene.background = new THREE.Color(0xf0f8ff); // 淡蓝色背景

    // 创建透视相机
    const aspectRatio = container.value.clientWidth / container.value.clientHeight;
    camera = new THREE.PerspectiveCamera(60, aspectRatio, 0.1, 1000);
    camera.position.set(0, 1.5, 5);

    // 创建渲染器
    renderer = new THREE.WebGLRenderer({ antialias: true });
    renderer.setSize(container.value.clientWidth, container.value.clientHeight);
    renderer.setPixelRatio(window.devicePixelRatio);
    renderer.shadowMap.enabled = true;
    renderer.shadowMap.type = THREE.PCFSoftShadowMap;

    // 添加渲染器到容器
    container.value.appendChild(renderer.domElement);

    // 添加轨道控制器
    controls = new OrbitControls(camera, renderer.domElement);
    controls.enableDamping = true;
    controls.dampingFactor = 0.05;
    controls.minDistance = 3;
    controls.maxDistance = 10;
    controls.maxPolarAngle = Math.PI / 1.5;

    // 添加灯光
    addLights();

    // 创建Q版二次元人物
    createAnimeCharacter();

    // 添加平面作为底座
    addSurface();

    // 开始动画
    animate();
};

// 添加灯光
const addLights = () => {
    // 环境光 - 柔和的粉色调
    const ambientLight = new THREE.AmbientLight(0xfff0f5, 0.6);
    scene.add(ambientLight);

    // 主方向光 - 明亮白光
    const mainLight = new THREE.DirectionalLight(0xffffff, 0.8);
    mainLight.position.set(5, 5, 5);
    mainLight.castShadow = true;

    // 优化阴影质量
    mainLight.shadow.mapSize.width = 1024;
    mainLight.shadow.mapSize.height = 1024;
    mainLight.shadow.camera.near = 0.5;
    mainLight.shadow.camera.far = 20;
    mainLight.shadow.radius = 2;

    const d = 8;
    mainLight.shadow.camera.left = -d;
    mainLight.shadow.camera.right = d;
    mainLight.shadow.camera.top = d;
    mainLight.shadow.camera.bottom = -d;

    scene.add(mainLight);

    // 补光 - 淡紫色
    const fillLight = new THREE.DirectionalLight(0xe6e6fa, 0.4);
    fillLight.position.set(-5, 3, -5);
    scene.add(fillLight);

    // 背光 - 淡蓝色轮廓光
    const backLight = new THREE.DirectionalLight(0xadd8e6, 0.3);
    backLight.position.set(0, 3, -5);
    scene.add(backLight);

    // 聚光灯 - 增加顶部高光
    const spotLight = new THREE.SpotLight(0xffffff, 0.5);
    spotLight.position.set(0, 6, 0);
    spotLight.angle = Math.PI / 6;
    spotLight.penumbra = 0.2;
    spotLight.decay = 1;
    spotLight.distance = 20;
    spotLight.castShadow = true;
    scene.add(spotLight);
};

// 添加平面作为底座
const addSurface = () => {
    // 创建一个圆形平台，比矩形更可爱
    const planeGeometry = new THREE.CircleGeometry(3, 32);
    const planeMaterial = new THREE.MeshStandardMaterial({
        color: 0xffd6e7, // 粉色平台
        roughness: 0.8,
        metalness: 0.2,
        side: THREE.DoubleSide
    });

    const plane = new THREE.Mesh(planeGeometry, planeMaterial);
    plane.rotation.x = -Math.PI / 2;
    plane.position.y = -0.7;
    plane.receiveShadow = true;
    scene.add(plane);

    // 添加一些装饰性的星星
    addDecorations();
};

// 添加装饰性元素
const addDecorations = () => {
    // 添加悬浮的星星
    const starGeometry = new THREE.OctahedronGeometry(0.15, 0);
    const starMaterial = new THREE.MeshStandardMaterial({
        color: 0xffff00,
        emissive: 0xffff99,
        emissiveIntensity: 0.5,
        metalness: 1,
        roughness: 0.2
    });

    // 创建几个星星并放置在不同位置
    const starPositions = [
        { x: -2, y: 1, z: -1 },
        { x: 2, y: 2, z: -1.5 },
        { x: -1.5, y: 3, z: 0 },
        { x: 1, y: 0.5, z: 2 }
    ];

    starPositions.forEach((pos, i) => {
        const star = new THREE.Mesh(starGeometry, starMaterial);
        star.position.set(pos.x, pos.y, pos.z);
        star.userData = {
            speed: 0.005 + Math.random() * 0.01,
            yOffset: i * Math.PI / 2  // 错开动画相位
        };
        scene.add(star);
    });

    // 添加一些漂浮的心形
    const heartShape = new THREE.Shape();
    const x = 0, y = 0;
    heartShape.moveTo(x, y);
    heartShape.bezierCurveTo(x + 0.2, y + 0.1, x + 0.3, y + 0.5, x, y + 0.5);
    heartShape.bezierCurveTo(x - 0.3, y + 0.5, x - 0.2, y + 0.1, x, y);

    const extrudeSettings = {
        depth: 0.1,
        bevelEnabled: true,
        bevelSegments: 2,
        steps: 1,
        bevelSize: 0.02,
        bevelThickness: 0.02
    };

    const heartGeometry = new THREE.ExtrudeGeometry(heartShape, extrudeSettings);

    // 创建3个心形
    const heartPositions = [
        { x: -1, y: 0, z: 2, color: 0xff5252 },  // 红心
        { x: 1.2, y: 0.3, z: 1.8, color: 0xba68c8 },  // 紫心
        { x: 0, y: 0.7, z: 2.5, color: 0x64b5f6 }   // 蓝心
    ];

    heartPositions.forEach((pos, i) => {
        const heartMaterial = new THREE.MeshStandardMaterial({
            color: pos.color,
            roughness: 0.4,
            metalness: 0.3
        });

        const heart = new THREE.Mesh(heartGeometry, heartMaterial);
        heart.position.set(pos.x, pos.y, pos.z);
        heart.scale.set(0.2, 0.2, 0.2);
        heart.rotation.z = Math.PI;
        heart.userData = {
            floatSpeed: 0.003 + Math.random() * 0.002,
            rotateSpeed: 0.01 + Math.random() * 0.01,
            yOffset: i * Math.PI / 1.5  // 错开动画相位
        };
        scene.add(heart);
    });
};

// 创建Q版二次元人物
const createAnimeCharacter = () => {
    // 人物组
    character = new THREE.Group();

    // 创建头部
    createHead();

    // 创建身体
    createBody();

    // 创建手臂
    createArms();

    // 创建腿部
    createLegs();

    // 初始角度
    character.rotation.y = -Math.PI / 6;

    // 将人物添加到场景
    scene.add(character);
};

// 创建头部
const createHead = () => {
    // 头部 - 略微椭圆形
    const headGeometry = new THREE.SphereGeometry(1, 32, 32);
    headGeometry.scale(1.1, 1.2, 1);

    const headMaterial = new THREE.MeshStandardMaterial({
        color: colors.skin,
        roughness: 0.3,
        metalness: 0
    });

    const head = new THREE.Mesh(headGeometry, headMaterial);
    head.position.y = 2;
    head.castShadow = true;
    character.add(head);

    // 眼睛
    createEyes();

    // 嘴巴
    createMouth();

    // 腮红
    createBlush();

    // 头发
    createHair();
};

// 创建眼睛
const createEyes = () => {
    // 左眼白
    const eyeWhiteGeometry = new THREE.SphereGeometry(0.25, 16, 16);
    const eyeWhiteMaterial = new THREE.MeshBasicMaterial({ color: 0xffffff });

    const leftEyeWhite = new THREE.Mesh(eyeWhiteGeometry, eyeWhiteMaterial);
    leftEyeWhite.position.set(-0.3, 2.1, 0.85);
    leftEyeWhite.scale.z = 0.1;
    character.add(leftEyeWhite);

    // 右眼白
    const rightEyeWhite = leftEyeWhite.clone();
    rightEyeWhite.position.x = 0.3;
    character.add(rightEyeWhite);

    // 左眼珠
    const eyeIrisGeometry = new THREE.SphereGeometry(0.12, 16, 16);
    const eyeIrisMaterial = new THREE.MeshBasicMaterial({ color: colors.eyes });

    const leftEyeIris = new THREE.Mesh(eyeIrisGeometry, eyeIrisMaterial);
    leftEyeIris.position.set(-0.3, 2.1, 0.95);
    character.add(leftEyeIris);

    // 右眼珠
    const rightEyeIris = leftEyeIris.clone();
    rightEyeIris.position.x = 0.3;
    character.add(rightEyeIris);

    // 左眼高光
    const highlightGeometry = new THREE.SphereGeometry(0.05, 8, 8);
    const highlightMaterial = new THREE.MeshBasicMaterial({ color: 0xffffff });

    const leftHighlight = new THREE.Mesh(highlightGeometry, highlightMaterial);
    leftHighlight.position.set(-0.35, 2.15, 1);
    character.add(leftHighlight);

    // 右眼高光
    const rightHighlight = leftHighlight.clone();
    rightHighlight.position.x = 0.25;
    character.add(rightHighlight);

    // 眉毛
    const eyebrowGeometry = new THREE.BoxGeometry(0.3, 0.05, 0.05);
    const eyebrowMaterial = new THREE.MeshBasicMaterial({ color: colors.hair });

    const leftEyebrow = new THREE.Mesh(eyebrowGeometry, eyebrowMaterial);
    leftEyebrow.position.set(-0.3, 2.4, 0.85);
    leftEyebrow.rotation.z = -0.2;
    character.add(leftEyebrow);

    const rightEyebrow = new THREE.Mesh(eyebrowGeometry, eyebrowMaterial);
    rightEyebrow.position.set(0.3, 2.4, 0.85);
    rightEyebrow.rotation.z = 0.2;
    character.add(rightEyebrow);
};

// 创建嘴巴
const createMouth = () => {
    // 使用弧线作为嘴巴
    const mouthShape = new THREE.Shape();
    mouthShape.moveTo(-0.15, 0);
    mouthShape.quadraticCurveTo(0, -0.1, 0.15, 0);

    const mouthGeometry = new THREE.ShapeGeometry(mouthShape);
    const mouthMaterial = new THREE.MeshBasicMaterial({ color: colors.mouth });

    const mouth = new THREE.Mesh(mouthGeometry, mouthMaterial);
    mouth.position.set(0, 1.7, 1);
    character.add(mouth);
};

// 创建腮红
const createBlush = () => {
    const blushGeometry = new THREE.CircleGeometry(0.15, 16);
    const blushMaterial = new THREE.MeshBasicMaterial({
        color: colors.blush,
        transparent: true,
        opacity: 0.6
    });

    const leftBlush = new THREE.Mesh(blushGeometry, blushMaterial);
    leftBlush.position.set(-0.6, 1.9, 0.7);
    leftBlush.rotation.y = Math.PI / 2.5;
    character.add(leftBlush);

    const rightBlush = leftBlush.clone();
    rightBlush.position.x = 0.6;
    rightBlush.rotation.y = -Math.PI / 2.5;
    character.add(rightBlush);
};

// 创建头发
const createHair = () => {
    // 使用几个部分组成头发

    // 头顶发型
    const topHairGeometry = new THREE.SphereGeometry(1.05, 32, 32);
    topHairGeometry.scale(1.15, 0.7, 1.05);

    const hairMaterial = new THREE.MeshStandardMaterial({
        color: colors.hair,
        roughness: 0.4,
        metalness: 0.1
    });

    const topHair = new THREE.Mesh(topHairGeometry, hairMaterial);
    topHair.position.set(0, 2.7, 0);
    character.add(topHair);

    // 侧面头发 - 左边
    const sideHairGeometry = new THREE.SphereGeometry(0.35, 16, 16);
    sideHairGeometry.scale(1, 1.8, 0.5);

    const leftSideHair = new THREE.Mesh(sideHairGeometry, hairMaterial);
    leftSideHair.position.set(-1, 1.8, 0.2);
    character.add(leftSideHair);

    // 侧面头发 - 右边
    const rightSideHair = leftSideHair.clone();
    rightSideHair.position.x = 1;
    character.add(rightSideHair);

    // 刘海
    const bangsGeometry = new THREE.CylinderGeometry(1, 0.9, 0.4, 16, 1, true);
    bangsGeometry.scale(1.1, 1, 1);

    const bangsMaterial = new THREE.MeshStandardMaterial({
        color: colors.hair,
        roughness: 0.4,
        metalness: 0.1,
        side: THREE.DoubleSide
    });

    const bangs = new THREE.Mesh(bangsGeometry, bangsMaterial);
    bangs.position.set(0, 2.4, 0.2);
    bangs.rotation.x = Math.PI / 12;
    character.add(bangs);

    // 额前发丝
    const hairStrandsGeometry = new THREE.BoxGeometry(0.15, 0.5, 0.1);

    const hairStrand1 = new THREE.Mesh(hairStrandsGeometry, hairMaterial);
    hairStrand1.position.set(-0.5, 2.35, 0.9);
    hairStrand1.rotation.x = -Math.PI / 6;
    hairStrand1.rotation.z = Math.PI / 8;
    character.add(hairStrand1);

    const hairStrand2 = new THREE.Mesh(hairStrandsGeometry, hairMaterial);
    hairStrand2.position.set(0, 2.4, 0.95);
    hairStrand2.rotation.x = -Math.PI / 6;
    character.add(hairStrand2);

    const hairStrand3 = new THREE.Mesh(hairStrandsGeometry, hairMaterial);
    hairStrand3.position.set(0.5, 2.35, 0.9);
    hairStrand3.rotation.x = -Math.PI / 6;
    hairStrand3.rotation.z = -Math.PI / 8;
    character.add(hairStrand3);

    // 发饰 - 星星
    const starShape = new THREE.Shape();
    const starRadius = 0.2;
    const starPoints = 5;
    const angleStep = Math.PI * 2 / starPoints;

    for (let i = 0; i < starPoints * 2; i++) {
        const radius = i % 2 === 0 ? starRadius : starRadius / 2;
        const angle = i * angleStep / 2 - Math.PI / 2;
        const x = Math.cos(angle) * radius;
        const y = Math.sin(angle) * radius;

        if (i === 0) {
            starShape.moveTo(x, y);
        } else {
            starShape.lineTo(x, y);
        }
    }

    const starExtrudeSettings = {
        depth: 0.05,
        bevelEnabled: true,
        bevelSegments: 2,
        steps: 1,
        bevelSize: 0.02,
        bevelThickness: 0.02
    };

    const starGeometry = new THREE.ExtrudeGeometry(starShape, starExtrudeSettings);
    const starMaterial = new THREE.MeshStandardMaterial({
        color: colors.hairAccessory,
        metalness: 0.3,
        roughness: 0.4
    });

    const hairStar = new THREE.Mesh(starGeometry, starMaterial);
    hairStar.position.set(-0.8, 2.3, 0.2);
    hairStar.rotation.z = Math.PI / 6;
    character.add(hairStar);
};

// 创建身体
const createBody = () => {
    // 连衣裙 - 上半部分
    const torsoGeometry = new THREE.CylinderGeometry(0.6, 0.8, 1.2, 16);
    const dressTopMaterial = new THREE.MeshStandardMaterial({
        color: colors.dress,
        roughness: 0.4,
        metalness: 0.1
    });

    const torso = new THREE.Mesh(torsoGeometry, dressTopMaterial);
    torso.position.y = 0.6;
    torso.castShadow = true;
    character.add(torso);

    // 连衣裙 - 下半部分
    const skirtGeometry = new THREE.ConeGeometry(1.5, 1, 16, 4);
    skirtGeometry.scale(1, -1, 1); // 翻转让小的一端在上

    const dressBottomMaterial = new THREE.MeshStandardMaterial({
        color: colors.dress,
        roughness: 0.4,
        metalness: 0.1
    });

    const skirt = new THREE.Mesh(skirtGeometry, dressBottomMaterial);
    skirt.position.y = 0;
    skirt.castShadow = true;
    character.add(skirt);

    // 领口装饰
    const collarGeometry = new THREE.TorusGeometry(0.4, 0.08, 8, 20, Math.PI);
    const collarMaterial = new THREE.MeshStandardMaterial({
        color: 0xffffff,
        roughness: 0.4,
        metalness: 0.1
    });

    const collar = new THREE.Mesh(collarGeometry, collarMaterial);
    collar.position.set(0, 1.15, 0.3);
    collar.rotation.x = Math.PI / 2;
    character.add(collar);
};

// 创建手臂
const createArms = () => {
    // 圆柱体手臂
    const armGeometry = new THREE.CylinderGeometry(0.15, 0.13, 1, 16);
    const armMaterial = new THREE.MeshStandardMaterial({
        color: colors.skin,
        roughness: 0.3,
        metalness: 0
    });

    // 左臂
    const leftArm = new THREE.Mesh(armGeometry, armMaterial);
    leftArm.position.set(-0.9, 0.6, 0);
    leftArm.rotation.z = Math.PI / 10;
    leftArm.castShadow = true;
    character.add(leftArm);

    // 右臂
    const rightArm = new THREE.Mesh(armGeometry, armMaterial);
    rightArm.position.set(0.9, 0.6, 0);
    rightArm.rotation.z = -Math.PI / 10;
    rightArm.castShadow = true;
    character.add(rightArm);

    // 手部
    const handGeometry = new THREE.SphereGeometry(0.15, 16, 16);
    const handMaterial = new THREE.MeshStandardMaterial({
        color: colors.skin,
        roughness: 0.3,
        metalness: 0
    });

    // 左手
    const leftHand = new THREE.Mesh(handGeometry, handMaterial);
    leftHand.position.set(-1.05, 0.1, 0);
    leftHand.castShadow = true;
    character.add(leftHand);

    // 右手
    const rightHand = new THREE.Mesh(handGeometry, handMaterial);
    rightHand.position.set(1.05, 0.1, 0);
    rightHand.castShadow = true;
    character.add(rightHand);
};

// 创建腿部
const createLegs = () => {
    // 腿部
    const legGeometry = new THREE.CylinderGeometry(0.15, 0.1, 0.8, 16);
    const legMaterial = new THREE.MeshStandardMaterial({
        color: colors.skin,
        roughness: 0.3,
        metalness: 0
    });

    // 左腿
    const leftLeg = new THREE.Mesh(legGeometry, legMaterial);
    leftLeg.position.set(-0.4, -0.9, 0);
    leftLeg.castShadow = true;
    character.add(leftLeg);

    // 右腿
    const rightLeg = new THREE.Mesh(legGeometry, legMaterial);
    rightLeg.position.set(0.4, -0.9, 0);
    rightLeg.castShadow = true;
    character.add(rightLeg);

    // 鞋子
    const shoeGeometry = new THREE.SphereGeometry(0.15, 16, 16);
    shoeGeometry.scale(1.2, 0.6, 1.5);

    const shoeMaterial = new THREE.MeshStandardMaterial({
        color: colors.shoes,
        roughness: 0.4,
        metalness: 0.2
    });

    // 左鞋
    const leftShoe = new THREE.Mesh(shoeGeometry, shoeMaterial);
    leftShoe.position.set(-0.4, -1.3, 0.05);
    leftShoe.castShadow = true;
    character.add(leftShoe);

    // 右鞋
    const rightShoe = new THREE.Mesh(shoeGeometry, shoeMaterial);
    rightShoe.position.set(0.4, -1.3, 0.05);
    rightShoe.castShadow = true;
    character.add(rightShoe);
};

// 动画循环
const animate = () => {
    animationId = requestAnimationFrame(animate);

    const elapsedTime = clock.getElapsedTime();

    // 角色轻微浮动动画
    if (character) {
        character.position.y = Math.sin(elapsedTime * 1.5) * 0.1;
        character.rotation.y = Math.sin(elapsedTime * 0.5) * 0.2 - Math.PI / 6;
    }

    // 动画装饰元素
    scene.children.forEach(child => {
        if (child.userData && child.userData.hasOwnProperty('speed')) {
            // 星星旋转和浮动
            child.rotation.y += child.userData.speed;
            child.position.y = child.userData.startY || child.position.y;
            child.position.y += Math.sin(elapsedTime + child.userData.yOffset) * 0.01;
        }

        if (child.userData && child.userData.hasOwnProperty('floatSpeed')) {
            // 心形旋转和浮动
            child.rotation.z += child.userData.rotateSpeed;
            child.position.y = child.userData.startY || child.position.y;
            child.position.y += Math.sin(elapsedTime + child.userData.yOffset) * 0.02;
        }
    });

    if (controls) {
        controls.update();
    }

    // 渲染场景
    renderer.render(scene, camera);
};

// 处理窗口大小变化
const handleResize = () => {
    if (container.value) {
        const width = container.value.clientWidth;
        const height = container.value.clientHeight;

        camera.aspect = width / height;
        camera.updateProjectionMatrix();
        renderer.setSize(width, height);
    }
};

// 保存初始Y位置
const saveInitialPositions = () => {
    scene.children.forEach(child => {
        if (child.userData && (child.userData.hasOwnProperty('speed') || child.userData.hasOwnProperty('floatSpeed'))) {
            child.userData.startY = child.position.y;
        }
    });
};

// 生命周期钩子
onMounted(() => {
    initThree();
    window.addEventListener('resize', handleResize);
    // 等待一帧确保所有元素都已创建
    setTimeout(saveInitialPositions, 100);
});

onBeforeUnmount(() => {
    window.removeEventListener('resize', handleResize);

    if (animationId) {
        cancelAnimationFrame(animationId);
    }

    if (controls) {
        controls.dispose();
    }

    // 清理Three.js资源
    if (renderer) {
        if (container.value && container.value.contains(renderer.domElement)) {
            container.value.removeChild(renderer.domElement);
        }
        renderer.dispose();
    }

    // 清理场景中的对象
    if (scene) {
        scene.traverse((object) => {
            if (object.geometry) {
                object.geometry.dispose();
            }
            if (object.material) {
                if (Array.isArray(object.material)) {
                    object.material.forEach(material => material.dispose());
                } else {
                    object.material.dispose();
                }
            }
        });
    }
});
</script>

<style scoped>
.notebook-3d-wrapper {
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 2rem 0;
}

.notebook-container {
    width: 100%;
    height: 400px;
    position: relative;
    border-radius: 8px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
    overflow: hidden;
}

@media (max-width: 768px) {
    .notebook-container {
        height: 300px;
    }
}
</style>